<template>
  <div class="checkin-management-container">
    <el-card class="filter-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3>签到签退管理</h3>
        </div>
      </template>

    </el-card>
    
    <el-card class="table-card" shadow="hover">
      <el-table
        :data="checkinList"
        border
        stripe
        highlight-current-row
        :row-key="row => row.id"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="activityName" label="活动名称" min-width="150" />
        <el-table-column prop="volunteerName" label="志愿者姓名" min-width="100" />
        <!-- <el-table-column prop="volunteerPhone" label="联系电话" min-width="120" /> -->
        <el-table-column label="签到时间" min-width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.checkinTime) }}
          </template>
        </el-table-column>
        <el-table-column label="签退时间" min-width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.checkoutTime) }}
          </template>
        </el-table-column>
        <el-table-column label="签到操作人" min-width="120">
          <template #default="{ row }">
            {{ row.checkinBy || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="签退操作人" min-width="120">
          <template #default="{ row }">
            {{ row.checkoutBy || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="评分" width="80" align="center">
          <template #default="{ row }">
            {{ row.score || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="评价" min-width="150">
          <template #default="{ row }">
            <el-tooltip content="点击查看评价" placement="top">
              <span @click="showComment(row)">{{ row.comment || '无评价' }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="签到状态" min-width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row)">{{ getStatusText(row) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" align="center">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              @click="handleCheckin(row)"
              :disabled="row.checkinTime"
            >
              <el-icon><check /></el-icon> 签到
            </el-button>
            <el-button 
              type="warning" 
              size="small" 
              @click="handleCheckout(row)"
              :disabled="!row.checkinTime || row.checkoutTime"
            >
              <el-icon><arrow-right /></el-icon> 签退
            </el-button>
            <el-button
              v-if="row.checkoutTime && !row.score"
              type="success"
              size="small"
              @click="openEvaluateDialog(row)"
            >
              <el-icon><star /></el-icon> 评价
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination" v-if="total > 0">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>
    </el-card>
    
    <!-- 评价对话框 -->
    <el-dialog
      v-model="evaluateDialogVisible"
      title="志愿者评价"
      width="30%"
    >
      <el-form :model="evaluateForm" :rules="evaluateRules" ref="evaluateFormRef">
        <el-form-item label="评分" prop="score">
          <el-input-number
            v-model="evaluateForm.score"
            :min="1"
            :max="5"
            placeholder="请选择评分"
            required
          />
        </el-form-item>
        <el-form-item label="评价内容" prop="comment">
          <el-input
            v-model="evaluateForm.comment"
            type="textarea"
            :rows="3"
            placeholder="请输入评价内容"
            maxlength="200"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="evaluateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEvaluation">提交评价</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElDialog, ElForm, ElInputNumber } from 'element-plus';
import {
  Search,
  Refresh,
  Check,
  ArrowRight,
  Star
} from '@element-plus/icons-vue';
import request from '@/utils/request';

// 搜索表单
const searchForm = reactive({
  activityName: '',
  volunteerName: '',
  checkinStatus: '',
  dateRange: []
});

// 表格数据
const checkinList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(false);

// 评价对话框
const evaluateDialogVisible = ref(false);
const evaluateForm = reactive({
  checkinId: null,
  score: null,
  comment: ''
});
const evaluateRules = reactive({
  score: [{ required: true, message: '请选择评分', trigger: 'change' }]
});

// 生命周期钩子
onMounted(() => {
  fetchCheckinList();
});

// 获取签到签退列表
const fetchCheckinList = async () => {
  loading.value = true;
  
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      activityName: searchForm.activityName || undefined,
      volunteerName: searchForm.volunteerName || undefined,
      checkinStatus: searchForm.checkinStatus || undefined,
      startTime: searchForm.dateRange?.[0] || undefined,
      endTime: searchForm.dateRange?.[1] || undefined
    };
    
    const response = await request.get('/signup-service/signup/checkin/list', { params }); // 修正路径
    
    if (response.code === 200) {
      checkinList.value = response.data.records || [];
      total.value = response.data.total || 0;
    } else {
      ElMessage.error(response.message || '获取签到记录失败');
    }
  } catch (error) {
    ElMessage.error('获取签到记录失败，请重试');
    console.error('API错误:', error);
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchCheckinList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.activityName = '';
  searchForm.volunteerName = '';
  searchForm.checkinStatus = '';
  searchForm.dateRange = [];
  currentPage.value = 1;
  fetchCheckinList();
};

// 处理签到
const handleCheckin = async (row) => {
  try {
    const response = await request.post('/signup-service/signup/checkin', { // 修正路径
      signupId: row.signupId,
      checkinBy: 3 // 实际应获取当前用户
    });
    
    if (response.code === 200) {
      ElMessage.success('签到成功');
      fetchCheckinList();
    } else {
      ElMessage.error(response.message || '签到失败');
    }
  } catch (error) {
    ElMessage.error('签到失败，请重试');
    console.error('签到错误:', error);
  }
};

// 处理签退
const handleCheckout = async (row) => {
  try {
    const response = await request.post('/signup-service/signup/checkout', { // 修正路径
      signupId: row.signupId,
      checkoutBy: 3
    });
    
    if (response.code === 200) {
      ElMessage.success('签退成功');
      fetchCheckinList();
    } else {
      ElMessage.error(response.message || '签退失败');
    }
  } catch (error) {
    ElMessage.error('签退失败，请重试');
    console.error('签退错误:', error);
  }
};

// 打开评价对话框
const openEvaluateDialog = (row) => {
  evaluateForm.checkinId = row.id;
  evaluateForm.score = null;
  evaluateForm.comment = '';
  evaluateDialogVisible.value = true;
};

// 提交评价
const submitEvaluation = async () => {
  if (!evaluateForm.checkinId) return;
  
  try {
    const response = await request.post('/signup-service/signup/evaluate', { // 新增评价接口
      checkinId: evaluateForm.checkinId,
      score: evaluateForm.score,
      comment: evaluateForm.comment
    });
    
    if (response.code === 200) {
      ElMessage.success('评价提交成功');
      evaluateDialogVisible.value = false;
      fetchCheckinList();
    } else {
      ElMessage.error(response.message || '评价提交失败');
    }
  } catch (error) {
    ElMessage.error('评价提交失败，请重试');
    console.error('评价错误:', error);
  }
};

// 状态处理
const getStatusText = (row) => {
  if (row.checkoutTime) return '已签退';
  if (row.checkinTime) return '已签到';
  return '未签到';
};

const getStatusType = (row) => {
  if (row.checkoutTime) return 'success';
  if (row.checkinTime) return 'warning';
  return 'info';
};

// 日期格式化
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-';
  return new Date(dateTime).toLocaleString().replace(/\//g, '-');
};
</script>

<style scoped lang="scss">
.checkin-management-container {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.table-card {
  min-height: 500px;
}

.el-table__fixed-right {
  right: 0;
}

.evaluate-btn {
  color: #409eff;
  cursor: pointer;
}

/* 评价对话框样式 */
.el-dialog {
  max-width: 400px;
}

.el-input-number {
  width: 100%;
}

.el-textarea__inner {
  min-height: 80px;
}
</style>